"use strict";

angular.module('app.yksensor').controller('TankChartsCtrl', function ($scope,$http,$cookieStore) {
    var device = {};
    var opt=window.location.hash.split('/');
    console.log(opt[2]);
    if(opt[2])
    {
       
      device.deviceid = opt[2];
    //   device.deviceid = "00010001"; //模拟数据
      //$("#deviceid_s").val = device.deviceid ;
      document.getElementById("deviceid_s").value=device.deviceid ;
      console.log(device)
      myAppGlobal.websockets.sensorSocket.emit("curve_history", device);
    
    //温度计列表
    $http.get('api/tank.json').success(function(res){
        for(var i=0; i<res.length; i++){
            if(res[i].id == device.deviceid){
                $scope.thermoInfo = res[i];
                // console.log($scope.thermoInfo)
            }
        }
    })
     
    }
    var temp = [], temp_time = [];
    var press = [], press_time = [];


    var sends = function () {

        // device.deviceid = $("#deviceid_s").val();
        device.deviceid = "00010001";
        device.timefrom = $("#time_s").val();
        device.timeto = $("#time_e").val();
        // console.log(device);
        myAppGlobal.websockets.sensorSocket.emit("curve_history", device);

    }

   myAppGlobal.websockets.sensorSocket.on("curve_history_return", function (items) {
         var i = 0;
         temp_time = items.map(function (item) {

             i++;
             return [i, item.time];
         });

         i = 0;

         temp = items.map(function (item) {

            i++;
            return [i, item.temp.toFixed(1)];
        });
        
         i = 0;
         press_time = items.map(function (item) {

             i++;
             return [i, item.time];
         });

         i = 0;

         press = items.map(function (item) {

             i++;
             return [i, item.press.toFixed(1)];
         });
        pagefunction();

    });
    


   $(document).ready(function () {

       $("#search").click(function () {
           sends();
         
        });
    });

    var plot_1, plot_2, plot_3, plot_4, plot_5, plot_6, plot_7, plot_8;



    // PAGE RELATED SCRIPTS

    var pagefunction = function() {
        /* chart colors default */
        var $chrt_border_color = "#efefef";
        var $chrt_grid_color = "#DDD"
        var $chrt_main = "#E24913";			/* red       */
        var $chrt_second = "#6595b4";		/* blue      */
        var $chrt_third = "#FF9F01";		/* orange    */
        var $chrt_fourth = "#7e9d3a";		/* green     */
        var $chrt_fifth = "#BD362F";		/* dark red  */
        var $chrt_mono = "#000";

        
        /* Sin chart temp */

        if ($("#sin-chart-t").length) {
            
            plot_2 = $.plot($("#sin-chart-t"), [{
                data : temp,
                label : "温度"
            }], {
                series : {
                    lines : {
                        show : true
                    },
                    points : {
                        show : true
                    }
                },
                grid : {
                    hoverable : true,
                    clickable : true,
                    tickColor : $chrt_border_color,
                    borderWidth : 0,
                    borderColor : $chrt_border_color,
                },
                tooltip : true,
                tooltipOpts : {
                    //content : "Value <b>$x</b> Value <span>$y</span>",
                    defaultTheme : false
                },
                colors : [$chrt_fourth, $chrt_second],
                yaxis : {
                    min : 5.1,
                    max : 100.1
                },
                xaxis : {
                    ticks:temp_time
                }
            });

            $("#sin-chart-t").bind("plothover", function (event, pos, item) {
                if (item) {
                    // console.log(item)
                    $("#flotTip").text(item.series.label + "值为 "+item.datapoint[1].toFixed(2)+" °C");
                    // console.log($('#flotTip').html())
                }
            });
        }

        /* end sin chart */


        /* Sin chart press */

        if ($("#sin-chart-p").length) {
        
            plot_2 = $.plot($("#sin-chart-p"), [{
                data: press,
                label: "液位"
            }], {
                series: {
                    lines: {
                        show: true
                    },
                    points: {
                        show: true
                    }
                },
                grid: {
                    hoverable: true,
                    clickable: true,
                    tickColor: $chrt_border_color,
                    borderWidth: 0,
                    borderColor: $chrt_border_color,
                },
                tooltip: true,
                tooltipOpts: {
                    //content : "Value <b>$x</b> Value <span>$y</span>",
                    defaultTheme: false
                },
                colors: [$chrt_second, $chrt_fourth],
                yaxis: {
                    min: 100,
                    max: 50000
                },
                xaxis: {
                    ticks: press_time
                }
            });

            $("#sin-chart-p").bind("plothover", function (event, pos, item) {
                if (item) {
                    // console.log(item)
                    $("#flotTip").text(item.series.label + "值为 "+item.datapoint[1].toFixed(2)+" m3");
                    // console.log($('#flotTip').html())
                }
            });
        }

        /* end sin chart */
    
        // START AND FINISH DATE
        $('#time_s').datepicker({
                //dateFormat : 'dd.mm.yy',
                dateFormat: 'yy-mm-dd',
                prevText: '<i class="fa fa-chevron-left"></i>',
                nextText: '<i class="fa fa-chevron-right"></i>',
                monthNames: ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'],  
                dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],  
                dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],  
                dayNamesMin: ['日','一','二','三','四','五','六'],
                onSelect: function (selectedDate) {
                    $('#time_e').datepicker('option', 'minDate', selectedDate);
                }
            });

            $('#time_e').datepicker({
                dateFormat: 'yy-mm-dd',
                prevText: '<i class="fa fa-chevron-left"></i>',
                nextText: '<i class="fa fa-chevron-right"></i>',
                monthNames: ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'],  
                dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],  
                dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],  
                dayNamesMin: ['日','一','二','三','四','五','六'],
                onSelect: function (selectedDate) {
                    $('#time_s').datepicker('option', 'maxDate', selectedDate);
                }
            });


    };

    // destroy generated instances
    // pagedestroy is called automatically before loading a new page
    // only usable in AJAX version!

    var pagedestroy = function(){

        //destroy flots
        plot_1.shutdown();
        plot_1 = null;

        plot_2.shutdown();
        plot_2 = null;

        plot_3.shutdown();
        plot_3 = null;

        plot_4.shutdown();
        plot_4 = null;

        plot_5.shutdown();
        plot_5 = null;

        plot_6.shutdown();
        plot_6 = null;

        plot_7.shutdown();
        plot_7 = null;

        plot_8.shutdown();
        plot_8 = null;

        if (debugState){
            root.console.log("✔ Flots destroyed");
        }

    }
    //pageSetUp();
    // load all flot plugins
    //loadScript("js/plugin/flot/jquery.flot.cust.min.js", function(){
    //	loadScript("js/plugin/flot/jquery.flot.resize.min.js", function(){
    //		loadScript("js/plugin/flot/jquery.flot.fillbetween.min.js", function(){
    //			loadScript("js/plugin/flot/jquery.flot.orderBar.min.js", function(){
    //				loadScript("js/plugin/flot/jquery.flot.pie.min.js", function(){
    //					loadScript("js/plugin/flot/jquery.flot.time.min.js", function(){
    //						loadScript("js/plugin/flot/jquery.flot.tooltip.min.js", pagefunction);
    //					});
    //				});
    //			});
    //		});
    //	});
    //});
    pagefunction();


    var datasets = {
        "usa": {
            label: "温度计1",
            data: [[1988, 48], [1989, 47], [1990, 45], [1991, 40], [1992, 42], [1993, 40], [1994, 37], [1995, 35], [1996, 33], [1997, 33], [1998, 32], [1999, 32], [2000, 34.2], [2001, 34.4], [2002, 38.7], [2003, 44], [2004, 48], [2005, 38], [2006, 52]]
        },        
        "russia": {
            label: "温度计2",
            data: [[1988, 21.8], [1989, 20.3], [1990, 17.1], [1992, 42.5], [1993, 37.6], [1994, 36.6], [1995, 21.7], [1996, 19.2], [1997, 21.3], [1998, 13.6], [1999, 14.0], [2000, 19.1], [2001, 21.3], [2002, 23.6], [2003, 25.1], [2004, 26.1], [2005, 31.1], [2006, 34.7]]
        },
        "uk": {
            label: "温度计3",
            data: [[1988, 29], [1989, 27], [1990, 26], [1991, 23], [1992, 26], [1993, 23], [1994, 29], [1995, 25], [1996, 24], [1997, 26], [1998, 21], [1999, 24], [2000, 28], [2001, 26], [2002, 25], [2003, 22], [2004, 26], [2005, 26], [2006, 23]]
        },
        "germany": {
            label: "温度计5",
            data: [[1988, 37], [1989, 35], [1990, 34], [1991, 34], [1992, 36], [1993, 39], [1994, 32], [1995, 38], [1996, 35], [1997, 34], [1998, 33], [1999, 32], [2000, 37], [2001, 34], [2002, 34], [2003, 34], [2004, 36], [2005, 30], [2006, 34]]
        },
        "denmark": {
            label: "温度计6",
            data: [[1988, 11.3], [1989, 11.9], [1990, 12.2], [1991, 18.9], [1992, 12.0], [1993, 13.0], [1994, 13.6], [1995, 19.8], [1996, 10.6], [1997, 15.5], [1998, 19.5], [1999, 17.3], [2000, 15.3], [2001, 17.4], [2002, 12.8], [2003, 11.8], [2004, 13.8], [2005, 16.7], [2006, 17.0]]
        },
        "sweden": {
            label: "温度计7",
            data: [[1988, 10.2], [1989, 17.4], [1990, 10.5], [1991, 10.9], [1992, 13.5], [1993, 12.0], [1994, 10.0], [1995, 11.8], [1996, 15.8], [1997, 18.0], [1998, 15.4], [1999, 17.8], [2000, 11.1], [2001, 19.3], [2002, 13.3], [2003, 19.1], [2004, 15.0], [2005, 12.1], [2006, 17.1]]
        },
        "norway": {
            label: "温度计8",
            data: [[1988, 28.2], [1989, 29.8], [1990, 23.5], [1991, 29.8], [1992, 26.6], [1993, 24.1], [1994, 27.0], [1995, 21.7], [1996, 27.5], [1997, 20.3], [1998, 28.2], [1999, 20.6], [2000, 25.8], [2001, 28.5], [2002, 26.9], [2003, 26.6], [2004, 29.4], [2005, 28.7], [2006, 29.1]]
        }
    };

    // hard-code color indices to prevent them from shifting as
    // countries are turned on/off

    var i = 0;
    $.each(datasets, function(key, val) {
        val.color = i;
        ++i;
    });

    // insert checkboxes 
    var choiceContainer = $("#choices");
    $.each(datasets, function(key, val) {
        // console.log(val)
        choiceContainer.append(
            // "<br/><input type='checkbox' name='" + key +
            // "' checked='checked' id='id" + key + "'></input>" +
            // "<label for='id" + key + "'>"
            // + val.label + "</label>"
            '<div class="col-xs-4 col-md-3 col-lg-2">'+
                '<div class="well text-center connect">'+
                    // '<img src="styles/img/avatars/gril1.png" alt="img" class="margin-bottom-5 margin-top-5">'+
                    '<div class="margin-bottom-5 margin-top-5" style="border-radius:50% 50% 0; background:#2b92ea; width:50px; height:50px; display:inline-block">'+
                        '<strong style="color:#fff; line-height:50px;">'+val.data[val.data.length-1][1].toFixed(1)+'°C</strong>'+
                    '</div>'+
                    '<br>'+
                    '<span class="font-xs"><b>'+val.label+'</b></span>'+
                    '<br>'+
                    '<span class="onoffswitch">'+
                        '<input type="checkbox" name="'+key+'" checked="checked" class="onoffswitch-checkbox ng-untouched ng-valid ng-dirty ng-valid-parse" id="id'+key+'">'+
                        '<label class="onoffswitch-label" for="id'+key+'">'+
                            '<span class="onoffswitch-inner" data-swchon-text="显示" data-swchoff-text="隐藏"></span>'+
                            '<span class="onoffswitch-switch"></span>'+
                        '</label>'+
                    '</span>'+
                '</div>'+
            '</div>'
        );
    });

    choiceContainer.find("input").click(plotAccordingToChoices);

    function plotAccordingToChoices() {

        var data = [];

        choiceContainer.find("input:checked").each(function () {
            var key = $(this).attr("name");
            if (key && datasets[key]) {
                data.push(datasets[key]);
            }
        });

        if (data.length > 0) {
            $.plot("#tempcharts", data, {
                series: {
                    lines: {
                        show: true,
                        lineWidth: 2
                    },
                    points:{
                        show: true
                    }
                },
                grid: { 
                    hoverable: true, 
                    clickable: true, 
                    tickColor: "#dddddd",
                    borderWidth: 2 
                },
                yaxis: {
                    min: 0,
                    tickDecimals: 2 //y轴小数点位数
                },
                xaxis: {
                    // mode: "time", //x轴显示时间数据格式
                    // tickSize:[1, "day"], //刻度标签会以每1天的间隔显示
                    // timeformat: "%Y/%m/%d", //刻度标签要输出的格式
                    // rotateTicks: 45, //jquery.flot.tickrotor 控制x轴过长时的倾斜
                    // labelWidth: 150,
                    // labelHeight: 150,
                    // reserveSpace: true,
                    tickDecimals: 0 //x轴小数点位数
                },
                legend: {//???
                    show: true,
                    noColumns: 0,
                        labelFormatter: function (label, series) {
                            return "<font size=\"2\" color=\"white\">" + label + "</font>";
                    },            
                    backgroundColor: "#000",
                    backgroundOpacity: 0.9,
                    labelBoxBorderColor: "#000000",
                    position: "nw"
                }
            });

            function showTooltip(x, y, contents) {
                $('<div id="tooltip">' + contents + '</div>').css( {
                    position: 'absolute',
                    display: 'none',
                    top: y + 5,
                    left: x + 5,
                    border: '1px solid #fdd',
                    padding: '2px',
                    'background-color': '#dfeffc',
                    opacity: 1,
                    'z-index': 1000
                }).appendTo("body").fadeIn(200);
            }

            var previousPoint = null;
            $("#tempcharts").bind("plothover", function (event, pos, item) {
                $("#x").text(pos.x);
                $("#y").text(pos.y.toFixed(2));

                if (item) {
                    if (previousPoint != item.dataIndex) {
                        previousPoint = item.dataIndex;

                        $("#tooltip").remove();
                        var x = new Date(item.datapoint[0]).toLocaleString(),//时间戳毫秒数转换成日期时间
                            y = item.datapoint[1].toFixed(2);

                        showTooltip(item.pageX, item.pageY,
                                    item.series.label + " 在 " + x + " 的值是 " + y +"°C");
                    }
                }
                else {
                    $("#tooltip").remove();
                        previousPoint = null;
                }
            }); 
            
        }
    }

    plotAccordingToChoices();



});

